package com.appbee.cm.client.nav.presenter;

import java.util.List;

import javax.inject.Inject;

import com.appbee.cm.client.nav.ui.ISimpleNavStyle;
import com.appbee.cm.shared.data.NavItemProxy;
import com.appbee.core.client.event.EntityChange;
import com.appbee.core.client.place.INamePlace;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceChangeEvent;
import com.google.gwt.user.client.ui.IsWidget;

public class SimpleNavPresenter
{
	private View view;
	private final NavControl navControl;
	private Long parentId = null;
	private final String displayType = "Auto";

	public interface View extends IsWidget
	{
		public void setData(List<NavItemWrap> data);

		public void setSelectedItem(NavItemWrap navItem);

		public void setNavStyle(ISimpleNavStyle navStyle);

	}

	@Inject
	public SimpleNavPresenter(	final NavControl navControl,
 EventBus eventBus)
	{
		this.navControl = navControl;
		eventBus.addHandler(PlaceChangeEvent.TYPE,
							new PlaceChangeEvent.Handler()
							{

								@Override
								public void onPlaceChange(PlaceChangeEvent event)
								{
									Place newPlace = event.getNewPlace();
									if (newPlace instanceof INamePlace)
									{
										INamePlace namePlace = (INamePlace) newPlace;
										NavItemWrap navItem = navControl
												.getByPlace(namePlace);
										view.setSelectedItem(navItem);
									}
								}
							});

		EntityChange
				.registerForProxyType(	eventBus,
										NavItemProxy.class,
										new EntityChange.Handler<NavItemProxy>()
										{

											@Override
											public void onChange(EntityChange<NavItemProxy> event)
											{
												view.setData(navControl
														.getChildrenByParentId(	parentId,
																				displayType));
											}

										});
	}

	public void setView(View view)
	{
		this.view = view;
		this.view.setData(navControl.getChildrenByParentId(	parentId,
															displayType));
	}

	public void setParentId(Long parentId)
	{
		this.parentId = parentId;
	}
}
